/**
 * Created by sakuri on 2017/5/16.
 * 播放进度条，写的不好爱用不用。
 */
;(function (window) {
    var cssClass = {},cssClassSub = {},bar = {},thePlayer;
    var isTouch = 'ontouchstart' in window,
        eStart = isTouch ? 'touchstart' : 'mousedown',
        eMove = isTouch ? 'touchmove' : 'mousemove',
        eEnd = isTouch ? 'touchend' : 'mouseup',
        eCancel = isTouch ? 'touchcancel' : 'mouseup';
    var option = {//内部参数
        classPrefix: 'audioplayer',
        strPlay: 'Play',
        strPause: 'Pause',
        strVolume: 'Volume'
    };

    var ready = {
        getPath: function(){
            var js = document.scripts, script = js[js.length - 1], jsPath = script.src;
            if(script.getAttribute('merge')) return;
            return jsPath.substring(0, jsPath.lastIndexOf("/") + 1);
        }(),
        loadStyles : function(){
            var csslist = [
                "css/audioplayer.css"
            ];
            var head = $('head')[0];
            var path = ready.getPath;
            $(csslist).each(function(){
                var link = document.createElement('link');
                link.rel = 'stylesheet';
                link.href = path + this;
                head.appendChild(link);
            });
        },
        secondsToTime : function (secs) {
            var hours = Math.floor(secs / 3600), minutes = Math.floor(secs % 3600 / 60),
                seconds = Math.ceil(secs % 3600 % 60);
            return ( hours == 0 ? '' : hours > 0 && hours.toString().length < 2 ? '0' + hours + ':' : hours + ':' ) + ( minutes.toString().length < 2 ? '0' + minutes : minutes ) + ':' + ( seconds.toString().length < 2 ? '0' + seconds : seconds );
        },

        extend_option : function(params){
            option = $.extend(option, params);
        },
        sub_css_sub : function(){
            cssClassSub = {
                playPause: 'playpause',
                playing: 'playing',
                time: 'time',
                timeCurrent: 'time-current',
                timeDuration: 'time-duration',
                bar: 'bar',
                barLoaded: 'bar-loaded',
                barPlayed: 'bar-played',
                volume: 'volume',
                browserFullscreen: 'browser-fullscreen',
                volumeButton: 'volume-button',
                volumeAdjust: 'volume-adjust',
                noVolume: 'novolume',
                mute: 'mute',
                mini: 'mini'
            };
            for (var subName in cssClassSub)
                cssClass[subName] = option.classPrefix + '-' + cssClassSub[subName];
        },
        draw : function(){
            thePlayer = $('<div class="' + option.classPrefix + '"><div class="' + cssClass.playPause + '" title="' + option.strPlay + '"><a href="#">' + option.strPlay + '</a></div></div>');
            thePlayer.append('<div class="' + cssClass.time + ' ' + cssClass.timeCurrent + '"></div><div class="' + cssClass.bar + '"><div class="' + cssClass.barLoaded + '"></div><div class="' + cssClass.barPlayed + '"></div></div><div class="' + cssClass.time + ' ' + cssClass.timeDuration + '"></div><div class="' + cssClass.browserFullscreen + '"><i class="fa fa-2x fa-square-o"></i></div><div class="' + cssClass.volume + '"><div class="' + cssClass.volumeButton + '" title="' + option.strVolume + '"><i class="fa fa-2x fa-volume-up"></i></div><div class="' + cssClass.volumeAdjust + '"><div><div></div></div></div></div>');
            ready.parts();
        },
        parts : function(){
            bar = {
                //bar 组成部分
                theBar : thePlayer.find('.' + cssClass.bar),//大概是整个进度条
                barPlayed : thePlayer.find('.' + cssClass.barPlayed),//已经播放的部分，进度条
                barLoaded : thePlayer.find('.' + cssClass.barLoaded),//已经加载的部分，进度条。如果有需求可以设置显示   barLoaded.width(( theAudio.buffered.end(0) / theAudio.duration ) * 100 + '%');
                timeCurrent : thePlayer.find('.' + cssClass.timeCurrent),//开始时间
                timeDuration : thePlayer.find('.' + cssClass.timeDuration),//结束时间
                browserFullscreen : thePlayer.find('.' + cssClass.browserFullscreen),//全屏按钮
                volumeButton : thePlayer.find('.' + cssClass.volumeButton),//音量按钮
                volumeAdjuster : thePlayer.find('.' + cssClass.volumeAdjust + ' > div'),//音量按钮鼠标悬停弹出框
                volumeDefault : 0,
                timeDurationSecs : 0
            };
        }
    };

    ready.loadStyles();//加载css

    //初始化
    var init = function () {
        var adjustCurrentTime = function (e) {
            var theRealEvent = isTouch ? e.originalEvent.touches[0] : e;
            var currentTime = Math.round(( bar.timeDurationSecs* ( theRealEvent.pageX - bar.theBar.offset().left ) ) / bar.theBar.width());
            progress.timeupdate(currentTime,bar.timeDurationSecs);
            if(typeof progress.changeCurrentTime == 'function'){
                progress.changeCurrentTime(currentTime)
            }
        },
        adjustVolume = function (e) {
            var theRealEvent = isTouch ? e.originalEvent.touches[0] : e;
            bar.volumeDefault = Math.abs(( theRealEvent.pageY - ( bar.volumeAdjuster.offset().top + bar.volumeAdjuster.height() ) ) / bar.volumeAdjuster.height());
            bar.volumeAdjuster.find('div').height(bar.volumeDefault * 100 + '%');
            if(typeof progress.changeVolume == 'function'){
                progress.changeVolume(bar.volumeDefault)
            }
            thePlayer.removeClass(cssClass.mute);
            thePlayer.find('i').removeClass('fa-volume-off');
            thePlayer.find('i').addClass('fa-volume-up');
        };

        //结束时间设置默认值 &hellip; = 省略号
        bar.timeDuration.html('&hellip;');
        //已经播放的部分计算设置默认值 0
        bar.timeCurrent.text(ready.secondsToTime(0));

        //拖动或触摸进度条的事件
        bar.theBar.on(eStart, function (e) {
            adjustCurrentTime(e);
            bar.theBar.on(eMove, function (e) {
                adjustCurrentTime(e);
            });
        }).on(eCancel, function () {//鼠标弹起事件
            bar.theBar.unbind(eMove);
        });

        bar.browserFullscreen.on('click', function () {
            if(typeof progress.browserFullscreen == 'function'){
                progress.browserFullscreen();
            }
            return false;
        });

        //点击音量按钮的时候静音切换
        bar.volumeButton.on('click', function () {
            if (thePlayer.hasClass(cssClass.mute)) {
                thePlayer.removeClass(cssClass.mute);
                thePlayer.find('i').removeClass('fa-volume-off');
                thePlayer.find('i').addClass('fa-volume-up');
                bar.volumeAdjuster.find('div').height(bar.volumeDefault * 100 + '%');
                if(typeof progress.changeVolume == 'function'){
                    progress.changeVolume(bar.volumeDefault)
                }
            }
            else {
                thePlayer.addClass(cssClass.mute);
                thePlayer.find('i').removeClass('fa-volume-up');
                thePlayer.find('i').addClass('fa-volume-off');
                bar.volumeAdjuster.find('div').height('0%');
                if(typeof progress.changeVolume == 'function'){
                    progress.changeVolume(0)
                }
            }
            return false;
        });
        //音量按钮弹出框拖动或触摸事件
        bar.volumeAdjuster.on(eStart, function (e) {
            adjustVolume(e);
            bar.volumeAdjuster.on(eMove, function (e) {
                adjustVolume(e);
            });
        }).on(eCancel, function () {//鼠标弹起事件
            bar.volumeAdjuster.unbind(eMove);
        });

        // playPause -- 播放暂停按钮点击事件
        thePlayer.find('.' + cssClass.playPause).on('click', function () {
            if (thePlayer.hasClass(cssClass.playing)) {
                $(this).attr('title', option.strPlay).find('a').html(option.strPlay);
                thePlayer.removeClass(cssClass.playing);
                if(typeof progress.pause == 'function'){
                    progress.pause()
                }
            }
            else {
                $(this).attr('title', option.strPause).find('a').html(option.strPause);
                thePlayer.addClass(cssClass.playing);
                if(typeof progress.play == 'function'){
                    progress.play()
                }
            }
            return false;
        });

    };

    //本体 内部方法
    var progress = {
        init : function(selector,params){
            ready.extend_option(params);
            ready.sub_css_sub();
            ready.draw();
            init();
            $(selector).replaceWith(thePlayer);
            return this;
        },
        /**
         * 加载数据。
         * @param duration 总长度
         * @param volume 音量
         */
        loadeddata : function(duration,volume){
            bar.timeDuration.text(ready.secondsToTime(duration));
            bar.volumeAdjuster.find('div').height(volume * 100 + '%');
            bar.volumeDefault = volume;
            bar.timeDurationSecs = duration;
        },
        /**
         * 设置播放位置。
         * @param currentTime 当前时间
         * @param duration 总长度
         */
        timeupdate : function(currentTime){
            bar.timeCurrent.text(ready.secondsToTime(currentTime));
            bar.barPlayed.width(( currentTime / bar.timeDurationSecs ) * 100 + '%');
        },
        /**
         * 设置音量。
         * @param volume 音量
         */
        volumechange : function(volume){
            bar.volumeAdjuster.find('div').height(volume * 100 + '%');
            if (volume > 0 && thePlayer.hasClass(cssClass.mute)) thePlayer.removeClass(cssClass.mute);
            if (volume <= 0 && !thePlayer.hasClass(cssClass.mute)) thePlayer.addClass(cssClass.mute);
            bar.volumeDefault = volume;
        },
        /**
         * 音量改变回调
         */
        changeVolume: null,
        /**
         * 当前播放时间改变回调
         */
        changeCurrentTime: null,
        /**
         * 暂停播放回调
         */
        pause: null,
        /**
         * 播放回调
         */
        play: null,
        /**
         * 切换全屏回调
         */
        browserFullscreen: null



    };

    window.progress = progress;
})(window);